package com.zsw.dubbo.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public class ClassLoaderUtil {

	private URLClassLoader ucl;
	private Method addURL;

	public ClassLoaderUtil() {
		this.ucl = (URLClassLoader) ClassLoader.getSystemClassLoader();
		try {
			this.addURL = URLClassLoader.class.getDeclaredMethod("addURL",
					new Class[] { URL.class });
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
	}

	public void addJar(String url) {
		addURL(url, "jar");
	}

	public void addClass(String url) {
		addURL(url, "class");
	}

	public void addJar(URL url) {
		addURL(url, "jar");
	}

	public void addClass(URL url) {
		addURL(url, "class");
	}

	public void addURL(String url, String type) {
		try {
			addURL(new File(url).toURI().toURL(), type);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}

	public void addURL(URL url, final String type) {
		try {
			addURL.setAccessible(true);
			File file = new File(url.getFile());
			if (file.isDirectory()) {
				File[] files = file.listFiles(new FilenameFilter() {
					public boolean accept(File dir, String name) {
						if (name.endsWith("." + type)) {
							return true;
						}
						return false;
					}
				});
				for (File f : files) {
					addURL.invoke(ucl, new Object[] { f.toURI().toURL() });
				}
			} else {
				addURL.invoke(ucl, new Object[] { url });
			}
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 使用ClassLoader,从根目录来获取资源
	 * 
	 * @param dir
	 *            包名+资源名
	 * @return
	 */
	public static InputStream getResource(String dir) {
		InputStream is = ClassLoaderUtil.class.getClassLoader()
				.getResourceAsStream(dir);
		return is;
	}

	public static String getText(String dir) {
		BufferedReader br = new BufferedReader(new InputStreamReader(
				getResource(dir)));
		String s = "";
		StringBuffer sb = new StringBuffer();
		try {
			while ((s = br.readLine()) != null) {
				sb.append(s);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	public URLClassLoader getUcl() {
		return ucl;
	}

	public void setUcl(URLClassLoader ucl) {
		this.ucl = ucl;
	}

	public Method getAddURL() {
		return addURL;
	}

	public void setAddURL(Method addURL) {
		this.addURL = addURL;
	}
}
